/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fait.ferm.persists;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Greg
 */
public class Plan_details_pay_credit extends PersistsObject {
    public int plan_id;
    public int credit_id;
    public double price;
    public Date date_performed;
    
    public Plan_details_pay_credit() {
        super();
        table = "plan_details_pay_credit";
    }
    
    public Plan_details_pay_credit(int pId) throws Exception {
        super(pId);
        table = "plan_details_pay_credit";
        load();
    }
    
    @Override
    public void load() throws Exception {
        boolean notSuccessfully=true;
		if(id==-1) {
			throw new Exception("Объект "+table+" отсутствует в базе");
		}	
		try (Statement st = con.createStatement()) {
			String q = "SELECT plan_id, credit_id, price, date_performed FROM "+table+" WHERE id = " + id;
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				notSuccessfully=false;
                plan_id = rs.getInt("plan_id");
                credit_id = rs.getInt("credit_id");
                price = rs.getDouble("price");
                date_performed = Date.valueOf(rs.getString("date_performed"));
			}
			rs.close();
		}
		if(notSuccessfully) {
			throw new Exception("Объект "+table+" не загружен");
        }
    }

    @Override
    protected void update() throws SQLException {
        try (Statement st = con.createStatement()) {
			String q = "UPDATE "+table+" SET date_performed="+date_performed.toString()+
					", price=" + price + ", credit_id=" + credit_id + ", plan_id=" + plan_id  + " " +
					"WHERE id = " + id;
			st.executeUpdate(q);
		}
    }

    @Override
    protected void createNew() throws SQLException, Exception {
        try (Statement st = con.createStatement()) {
			String q = "INSERT INTO "+table+" "+
					"(date_performed, price, credit_id, plan_id) VALUES("+
						date_performed.toString() + ","+
						price +
                        credit_id +
                        plan_id +
					")";
			st.executeUpdate(q);
			q="SELECT seq FROM sqlite_sequence WHERE name = '"+table+"'";
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				id = rs.getInt("seq");
			}
			rs.close();
		}
    }
    
}
